"""
用户仓储
"""
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.user import User
from app.schemas.user import UserCreate, UserUpdate
from app.repositories.base import BaseRepository


class UserRepository(BaseRepository[User, UserCreate, UserUpdate]):
    """用户仓储"""
    
    def __init__(self):
        super().__init__(User)
    
    async def get_by_username(self, db: AsyncSession, *, username: str) -> Optional[User]:
        """根据用户名获取用户"""
        return await self.get_by_field(db, "username", username)
    
    async def get_by_email(self, db: AsyncSession, *, email: str) -> Optional[User]:
        """根据邮箱获取用户"""
        return await self.get_by_field(db, "email", email)
    
    async def get_by_username_or_email(
        self, 
        db: AsyncSession, 
        *, 
        identifier: str
    ) -> Optional[User]:
        """根据用户名或邮箱获取用户"""
        stmt = select(User).where(
            (User.username == identifier) | (User.email == identifier)
        )
        result = await db.execute(stmt)
        return result.scalar_one_or_none()
    
    async def is_username_taken(self, db: AsyncSession, *, username: str) -> bool:
        """检查用户名是否被占用"""
        return await self.exists(db, username=username)
    
    async def is_email_taken(self, db: AsyncSession, *, email: str) -> bool:
        """检查邮箱是否被占用"""
        return await self.exists(db, email=email)
    
    async def get_active_users(self, db: AsyncSession, *, skip: int = 0, limit: int = 100):
        """获取活跃用户列表"""
        return await self.get_multi(
            db, 
            skip=skip, 
            limit=limit, 
            filters={"is_active": True}
        )
    
    async def search_users(
        self, 
        db: AsyncSession, 
        *, 
        keyword: str, 
        skip: int = 0, 
        limit: int = 100
    ):
        """搜索用户"""
        stmt = select(User).where(
            (User.username.like(f"%{keyword}%")) |
            (User.full_name.like(f"%{keyword}%")) |
            (User.email.like(f"%{keyword}%")) |
            (User.organization.like(f"%{keyword}%"))
        ).offset(skip).limit(limit)
        
        result = await db.execute(stmt)
        return result.scalars().all()


# 创建仓储实例
user_repository = UserRepository()